/*
 * @Author: 糊涂的老知青
 * @Date: 2022-09-01
 * @Version: 1.0.0
 * @Description:
 */
package httpclient

import (
	"errors"
	"lzq-admin/config"
	"lzq-admin/pkg/cache"
	"strings"

	jsoniter "github.com/json-iterator/go"
)

type IpRspDto struct {
	Success bool      `json:"success"`
	Ip      string    `json:"ip"`
	Info    IpInfoDto `json:"info"`
}
type IpInfoDto struct {
	Country  string `json:"country"`
	Prov     string `json:"prov"`
	City     string `json:"city"`
	Lsp      string `json:"lsp"`
	PostCode string `json:"postcode"`
}

func GetIpArea(ip string) (IpInfoDto, error) {
	igoreIps := []string{"::1", "localhost", "127.", "192.168."}
	for _, v := range igoreIps {
		if ip == v || strings.HasPrefix(ip, v) {
			return IpInfoDto{}, nil
		}
	}
	cacheKey := "IpAreaInfo"
	cacheObj := cache.RedisUtil.NewRedis(nil, false, "pkg:httpclient").HGet(cacheKey, ip)
	if len(cacheObj) > 0 {
		var ipInfoDto IpInfoDto
		if err := jsoniter.UnmarshalFromString(cacheObj, &ipInfoDto); err != nil {
			return ipInfoDto, err
		}
	}
	ipArea := config.ViperConfig.GetString("server.IpArea")
	statusCode, rspJson, err := HttpGet(ipArea+"?ip="+ip, nil)
	var rspDto IpRspDto
	if err != nil {
		return rspDto.Info, err
	}
	if statusCode >= 200 && statusCode < 300 {
		var rspDto IpRspDto
		if err := jsoniter.UnmarshalFromString(rspJson, &rspDto); err != nil {
			return rspDto.Info, err
		}
		if rspDto.Success == false {
			return rspDto.Info, errors.New(rspJson)
		}
		cache.RedisUtil.NewRedis(nil, false, "pkg:httpclient").HSet(cacheKey, ip, rspDto.Info, 0)
		return rspDto.Info, nil
	}
	return rspDto.Info, errors.New(rspJson)
}
